import 'package:flutter/material.dart';
import 'dart:convert';
import '../models/memory.dart';
import '../models/timeline_event.dart';
import '../repositories/timeline_repository.dart';

class TimelineProvider extends ChangeNotifier {
  final TimelineRepository _repository;
  List<Memory> _memories = [];
  List<TimelineEvent> _events = [];
  bool _isLoading = false;
  String? _error;
  
  List<Memory> get memories => List.unmodifiable(_memories);
  List<TimelineEvent> get events => List.unmodifiable(_events);
  bool get isLoading => _isLoading;
  String? get error => _error;

  TimelineProvider(this._repository) {
    _loadMemories();
    _loadEvents();
  }

  Future<void> _loadMemories() async {
    _setLoading(true);
    
    try {
      final response = await _repository.getAllMemories();
      if (response.isSuccess && response.data != null) {
        _memories = response.data!;
        _clearError();
      } else {
        _setError(response.error ?? '获取回忆数据失败');
      }
    } catch (e) {
      _setError('获取回忆数据失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _saveMemories() async {
    // 这个方法不再需要，在 Repository 层处理
  }

  Future<void> addMemory(Memory memory) async {
    _setLoading(true);
    
    try {
      final response = await _repository.createMemory(memory);
      if (response.isSuccess && response.data != null) {
        _memories.add(response.data!);
        _memories.sort((a, b) => b.date.compareTo(a.date));
        _clearError();
      } else {
        _setError(response.error ?? '添加回忆失败');
      }
    } catch (e) {
      _setError('添加回忆失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> updateMemory(String id, Memory updatedMemory) async {
    _setLoading(true);
    
    try {
      final response = await _repository.updateMemory(updatedMemory);
      if (response.isSuccess && response.data != null) {
        final index = _memories.indexWhere((memory) => memory.id == id);
        if (index != -1) {
          _memories[index] = response.data!;
          _memories.sort((a, b) => b.date.compareTo(a.date));
          _clearError();
        }
      } else {
        _setError(response.error ?? '更新回忆失败');
      }
    } catch (e) {
      _setError('更新回忆失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> deleteMemory(String id) async {
    _setLoading(true);
    
    try {
      final response = await _repository.deleteMemory(id);
      if (response.isSuccess) {
        _memories.removeWhere((memory) => memory.id == id);
        _clearError();
      } else {
        _setError(response.error ?? '删除回忆失败');
      }
    } catch (e) {
      _setError('删除回忆失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Memory? getMemoryById(String id) {
    try {
      return _memories.firstWhere((memory) => memory.id == id);
    } catch (e) {
      return null;
    }
  }

  Future<void> _loadEvents() async {
    _setLoading(true);
    
    try {
      final response = await _repository.getAllEvents();
      if (response.isSuccess && response.data != null) {
        _events = response.data!;
        _clearError();
      } else {
        _setError(response.error ?? '获取时间线事件数据失败');
      }
    } catch (e) {
      _setError('获取时间线事件数据失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _saveEvents() async {
    // 这个方法不再需要，在 Repository 层处理
  }

  Future<void> addEvent(TimelineEvent event) async {
    _setLoading(true);
    
    try {
      final response = await _repository.createEvent(event);
      if (response.isSuccess && response.data != null) {
        _events.add(response.data!);
        _events.sort((a, b) => b.date.compareTo(a.date));
        _clearError();
      } else {
        _setError(response.error ?? '添加时间线事件失败');
      }
    } catch (e) {
      _setError('添加时间线事件失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> updateEvent(String id, TimelineEvent updatedEvent) async {
    _setLoading(true);
    
    try {
      final response = await _repository.updateEvent(updatedEvent);
      if (response.isSuccess && response.data != null) {
        final index = _events.indexWhere((event) => event.id == id);
        if (index != -1) {
          _events[index] = response.data!;
          _events.sort((a, b) => b.date.compareTo(a.date));
          _clearError();
        }
      } else {
        _setError(response.error ?? '更新时间线事件失败');
      }
    } catch (e) {
      _setError('更新时间线事件失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> deleteEvent(String id) async {
    _setLoading(true);
    
    try {
      final response = await _repository.deleteEvent(id);
      if (response.isSuccess) {
        _events.removeWhere((event) => event.id == id);
        _clearError();
      } else {
        _setError(response.error ?? '删除时间线事件失败');
      }
    } catch (e) {
      _setError('删除时间线事件失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  TimelineEvent? getEventById(String id) {
    try {
      return _events.firstWhere((event) => event.id == id);
    } catch (e) {
      return null;
    }
  }
  
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
  
  void _setError(String error) {
    _error = error;
    notifyListeners();
  }
  
  void _clearError() {
    _error = null;
    notifyListeners();
  }
}
